// pages/tools/wangdian/select/select.js
//获取应用实例
var app = getApp();
const util = require("../../../../utils/util");
var QQMapWX = require('../../../../utils/qqmap-wx-jssdk1.2/qqmap-wx-jssdk.min.js');
var qqmapsdk = new QQMapWX({
  key: 'KR7BZ-XSQ3P-VGFD7-LNRZL-E7PXE-STF76'
});

let defaultCity;
Page({

  /**
   * 页面的初始数据
   */

  data: {
    type: ['网点', '业务'],
    typeIndex: 0,
    keywords: '',
    history: [],
    webInfo: [],
    shwoHistory: true,
    range: '',
    showPop: false,
    opentype: '',
    data: {},
    hotSearch: "",
    cityCode: 'sz',
    lat: '',
    lng: '',
    isLast: false, //是否最后一页
    count: 0, //总条数
    page: 1, //第几页
    provinceName: '广州市',
    cityName: '深圳市',
    districtName: '南山区',
    local: '深圳市', //显示地点
    province: [],
    provinceIndex: 0,
    city: [],
    cityIndex: 0,
    district: [],
    districtIndex: 0,
    showAddress: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    util.getUrl(app.globalData.url).then(e => {
      util.request('network.php', {
        action: 'get_citys'
      }, 'POST').then(res => {
        if (res.data.state == 1) {
          res.data.data.forEach(item => (item.chouse = false));
          res.data.data.unshift({
            cityname: '默认',
            citycode: 'mr',
            id: 0,
            chouse: true
          });
          this.setData({
            province: res.data.data
          })
          
          util.request('network.php', {
            action: 'get_cityid',
            cityname: options.cityName || this.data.cityName
          }, 'POST').then(res => {
            this.setData({
              city: res.data.data
            })
            defaultCity = JSON.parse(JSON.stringify(this.data.city));
            qqmapsdk.reverseGeocoder({
              success: () => {},
              fail: () => {},
              complete: (res) => {
                ks.setStorageSync('lat', res.result.location.lat)
                ks.setStorageSync('lng', res.result.location.lng)
                const lat = res.result ? res.result.location.lat : ''
                const lng = res.result ? res.result.location.lng : ''
                this.data.history = ks.getStorageSync('history') ? JSON.parse(ks.getStorageSync('history')) : '';
                this.data.keywords = options.keywords;
                this.setData({
                  history: this.data.history,
                  keywords: this.data.keywords,
                  typeIndex: options.type ? parseInt(options.type) - 1 : 0,
                  lat,
                  lng,
                  provinceName: options.provinceName || this.data.provinceName,
                  cityName: options.cityName || this.data.cityName,
                  districtName: options.districtName || this.data.districtName,
                  cityCode: options.cityCode,
                  local: options.districtName == '全部' ? options.cityName : options.cityName + options.districtName
                })
                if (this.data.keywords) {
                  this.getInfo()
                };
                this.getHotSearch();
                this.getDistrict(this.data.districtName)
              }
            })
          })

        }
      })
    })
  },
  // 开关选择城市
  toggleAddress() {
    this.setData({
      showAddress: !this.data.showAddress
    })
  },
  // 选择城市
  addressClick(e) {
    let index = util.getValue('index', e)
    let type = util.getValue('type', e)
    this.data[`${type}Index`] = index;
    this.data[type].forEach(item => (item.chouse = false));
    let data = this.data[type][index];
    data.chouse = true;
    this.setData({
      [`${type}Index`]: this.data[`${type}Index`],
      [type]: this.data[type]
    })
    switch (type) {
      case 'province': {
        this.setData({
          district: []
        })
        if (data.cityname == '默认') {
          this.setData({
            city: defaultCity
          })
        } else {
          this.getCity();
        }
      }
      break;
    case 'city':
      this.getDistrict();
      break;
    case 'district': {
      this.data.showAddress = false;
      let district = this.data.district[this.data.districtIndex].id ? this.data.district[this.data.districtIndex].cityname : '全部';
      this.data.local = `${this.data.city[this.data.cityIndex].cityname}${this.data.district[this.data.districtIndex].cityname}`;
      this.setData({
        showAddress: this.data.showAddress,
        local: this.data.local,
        provinceName: this.data.province[this.data.provinceIndex].cityname,
        cityName: this.data.city[this.data.cityIndex].cityname,
        districtName: district,
        cityCode: this.data.city[this.data.cityIndex].citycode
      })
      this.search()
    }
    break;
    default: {}
    }
  },
  // 获得城市
  getCity() {
    if (!this.data.province[this.data.provinceIndex].city)
      util.request('network.php', {
        action: 'get_citys',
        proviceid: this.data.province[this.data.provinceIndex].id
      }, 'POST').then(res => {
        if (res.data.state == 1) {
          res.data.data.forEach(item => (item.chouse = false));
          this.data.city = res.data.data;
          this.data.province[this.data.provinceIndex].city = res.data.data;
          this.setData({
            city: this.data.city,
            getCity: this.data.province
          })

        }
      });
    else {
      this.data.city = this.data.province[this.data.provinceIndex].city
      this.setData({
        city: this.data.city
      })
    }

  },
  // 获得区
  getDistrict(district) {
    if (this.data.city[this.data.cityIndex].district) {
      this.data.district = this.data.city[this.data.cityIndex].district;
      this.data.districtIndex = this.data.district.findIndex(item => item.cityname == district)
      this.setData({
        district: this.data.city[this.data.cityIndex].district,
        districtIndex: this.data.districtIndex
      })
    } else {
      util.request('network.php', {
        action: 'get_citys',
        cityid: this.data.city[this.data.cityIndex].id
      }, 'POST').then(res => {
        if (res.data.state == 1) {
          res.data.data.forEach(item => (item.chouse = false));
          res.data.data.unshift({
            id: '',
            citycode: '',
            cityname: '全市'
          });
          this.data.district = res.data.data;
          this.data.city[this.data.cityIndex].district = this.data.district;
          this.data.districtIndex = this.data.district.findIndex(item => item.cityname == district);
          this.setData({
            district: this.data.district,
            city: this.data.city,
            districtIndex: this.data.districtIndex
          })
        }
      });
    }
  },
  //双向绑定keywords
  keywords(e) {
    this.setData({
      keywords: e.detail.value
    })
  },
  // 类型切换
  typeChange(e) {
    this.setData({
      typeIndex: parseInt(e.detail.value)
    })
    this.getHotSearch();
  },
  // 关键字搜索
  setKeywords(e) {
    let name = util.getValue('name', e)
    let type = util.getValue('type', e)
    this.setData({
      keywords: name,
      typeIndex: parseInt(type) - 1
    })
    this.setData({
      page: 1,
      webInfo: []
    })
    this.getInfo();
  },
  // 搜索
  search() {
    if (this.data.keywords.trim()) {
      util.addHistory({
        name: this.data.keywords,
        type: parseInt(this.data.typeIndex) + 1
      });
    }
    this.setData({
      page: 1,
      webInfo: []
    })
    this.getInfo();
  },
  //获取热门评论
  getHotSearch() {
    util.request("network.php", {
      citycode: this.data.cityCode,
      type: this.data.type[this.data.typeIndex],
      action: "hot",
    }, "POST").then(res => {

      if (res.data) {
        this.setData({
          hotSearch: res.data
        })
      }
    })
  },
  //获取列表
  getInfo() {
    let data = {
      keywords: this.data.keywords,
      lat: this.data.lat,
      lnt: this.data.lng,
      type: parseInt(this.data.typeIndex) + 1,
      provice: this.data.provinceName,
      city: this.data.cityName,
      county: this.data.districtName,
      page: this.data.page,
      action: 'search'
    };
    ks.showLoading({
      title: '加载中',
      mask: true
    })
    util.request('network.php', data, 'POST').then(res => {
     
      if (res.data.data.search.length) {
        res.data.data.search.forEach(item => {
          this.setData({
            shwoHistory: false
          })
          if (item.distance) {
            item.distance = item.distance < 1 ? `${(parseFloat(item.distance) * 1000).toFixed(0)}米` : `${parseFloat(item.distance).toFixed(2)}公里`
          }
        });
        this.setData({
          webInfo: this.data.webInfo.concat(res.data.data.search),
          count: res.data.count,
          isLast: false
        })
        if (this.data.webInfo.length >= this.data.count) {
          this.setData({
            isLast: true
          })
        }
        ks.hideLoading()
      } else {
        ks.hideLoading()
        this.setData({
          isLast: true
        })
        ks.showToast({
          title: '没有更多数据了',
          icon: 'none'
        });

      }

    }).catch(err => ks.hideLoading());

  },
  //业务信息
  shwoDetail(options) {
    let index = util.getValue('index', options)
    util.request(
      'network.php', {
        action: 'service',
        id: this.data.webInfo[index].id
      },
      'POST'
    ).then(e => {
      e.data[0].work ? ks.showModal({
        title: '业务范围',
        content: e.data[0].work,
        confirmText: '关闭',
        showCancel: false
      }) : ks.showToast({
        title: '暂无业务信息',
        icon: 'none'
      })

    })
  },
  toDetail(e) {
    let index = util.getValue('index', e)
    ks.navigateTo({
      url: `../detail/detail?detailId=${this.data.webInfo[index].id}&cityName=${this.data.cityName}&lat=${this.data.lat}&lng=${this.data.lng}`
    });
  },
  // 打开地图
  navigator(options) {
   
    let latitude = parseFloat(util.getValue('lat', options))
    let longitude = parseFloat(util.getValue('lng', options))
    const location = util.bMapTransQQMap(longitude, latitude)
    longitude = location.lng
    latitude = location.lat
    let name = util.getValue('name', options)
    let address = util.getValue('addr', options)
    let urls = encodeURIComponent(
        // `https://map.qq.com/m/index/nav/type=bus&cond=3&sword=我的位置&spointy=${this.data.locLatitude}&spointx=${this.data.locLongitude}&eword=${enp.name}`
        `https://map.qq.com/m/place/result/city=${this.data.cityName}&word=${name}&mode=map/`
        )
    ks.navigateTo({
        url: `/pages/webview/webview?path=${urls}`
    });
    ks.openLocation({
      latitude,
      longitude,
      name,
      address
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.data.isLast) {
      this.setData({
        page: this.data.page + 1
      })
      this.getInfo()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: `本地宝-网点查询-${this.data.keywords}-查询`,
      imageUrl: "http://imgbdb3.bendibao.com/xcxbdb/file/20212/9/20210209161843_68677.jpg",
      path: `/pages/tools/wangdian/select/select?keywords=${this.data.keywords}&type=${this.data.typeIndex+1}&provinceName=${this.data.provinceName}&cityName=${this.data.cityName}&districtName=${this.data.districtName}&cityCode=${this.data.cityCode}`,
    }
  }
})